package org.geektimes.projects.user.validator.bean.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MobileValidAnnotationValidator implements ConstraintValidator<MobileValid, String> {

    private final String MOBILE_REX = "\\d{1}\\d{10}";

    private final Pattern localPattern;

    public MobileValidAnnotationValidator() {
        this.localPattern = Pattern.compile(MOBILE_REX);
    }

    private MobileValid annotation;
    @Override
    public void initialize(MobileValid annotation) {
        this.annotation = annotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.length() == 0) {
            return false;
        }
        if(matchPart(value, localPattern)) {
            return true;
        } else {
            context.disableDefaultConstraintViolation();//禁用默认的message的值
            //重新添加错误提示语句
            context.buildConstraintViolationWithTemplate(annotation.message()).addConstraintViolation();
            return false;
        }
    }

    private boolean matchPart(String part, Pattern pattern) {

        Matcher matcher = pattern.matcher(part);
        return matcher.matches();
    }
}
